<?php

use Illuminate\Support\Facades\Route;
use Illuminate\Http\Request;
use App\Http\Controllers\LoginController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
| 
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
| 
*/

Route::get('/', function () {
    return view('welcome');
});

Route::get('/captchaImage', function () {
    $captcha = app('captcha')->create('default', true);
    $captcha['img'] = str_replace('data:image/png;base64,', '', $captcha['img']);
    return response()->json([
        'captchaEnabled' => true,
        'code' => 200,
        'msg' => 'success',
        'img' => $captcha['img'],
        'uuid' => $captcha['key'],
    ]);
});

Route::post('/verify-captcha', function (Request $request) {
    $validator = validator($request->all(), [
        'code' => 'required|string',
        'uuid' => 'required|string',
    ]);

    if ($validator->fails()) {
        return response()->json([
            'msg' => '验证码错误',
            'code' => 1,
        ]);
    }

    $captcha = captcha_check($request->code, $request->uuid);

    if ($captcha) {
        $newCaptcha = captcha();
        preg_match('/data:image\/png;base64,(.*)/', $newCaptcha['img'], $matches);
        $base64Image = isset($matches[1]) ? $matches[1] : '';
        return response()->json([
            'msg' => '验证成功',
            'code' => 0,
            'img' => $base64Image,
            'uuid' => $newCaptcha['key']
        ]);
    } else {
        $newCaptcha = captcha();
        preg_match('/data:image\/png;base64,(.*)/', $newCaptcha['img'], $matches);
        $base64Image = isset($matches[1]) ? $matches[1] : '';
        return response()->json([
            'msg' => '验证码错误',
            'code' => 1,
            'img' => $base64Image,
            'uuid' => $newCaptcha['key']
        ]);
    }
});

Route::post('/login', [LoginController::class, 'login'])->middleware('throttle:5,1'); // 限制每分钟最多5次请求


Route::get('/getInfo', [LoginController::class, 'getInfo']);

